package com.apes.scm.stock.transfer.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.scm.account.account.service.ProductAccountService;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.service.TaxService;
import com.apes.scm.masterdata.product.service.UomService;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrder;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrderItem;
import com.apes.scm.pur.purchaseOrder.repository.PurchaseOrderRepository;
import com.apes.scm.pur.purchaseOrder.service.PurchaseService;
import com.apes.scm.stock.transfer.model.Pick;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.model.VoucherItem;
import com.apestech.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/*
 * 流转到采购凭证(未回写采购订单收货状态,开票状态)
* */
@Service("pickFlowPurchaseVoucherService")
public class PickFlowPurchaseVoucherService extends DomainService {

    @Autowired
    PurchaseOrderRepository purchaseOrderRepository;
    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    ProductAccountService productAccountService;

    @Autowired
    UomService uomService;


    public Voucher flowPurchaseVoucher(SimpleRequest simpleRequest) {
        Pick pick = simpleRequest.getO(Pick.class);
        PurchaseOrder purchaseOrder = purchaseOrderRepository.findOne(pick.getOrigin());
        if (purchaseOrder == null) throw new RuntimeException(pick.getOrigin() + "采购订单不存在！");
        Voucher voucher = new Voucher();
        // 主表信息
        if (purchaseOrder.getSupplier().getParty().getName().indexOf("巴图鲁") != -1) voucher.setThirdTime(purchaseOrder.getDateApprove());
        voucher.setCompany(purchaseOrder.getCompany());
        voucher.setCustomerExpand(purchaseOrder.getCustomerExpandId());
        voucher.setDept(purchaseOrder.getDept());
        voucher.setClerk(purchaseOrder.getClerk()); //业务员
        voucher.setContract(purchaseOrder.getContract());//采购合同
        voucher.setPartner(purchaseOrder.getSupplier());
        voucher.setInventoryMode(purchaseOrder.getCooperation().getInventoryMode());
        voucher.setAccountingMethod(purchaseOrder.getCooperation().getAccountingMethod());
        voucher.setScene(purchaseOrder.getScene());
        voucher.setOrigin(purchaseOrder.getId());
        voucher.setOriginBusinessType(pick.getOriginBusinessType());
        voucher.setSource(pick.getId());
        voucher.setSourceBusinessType(pick.getInnerBusinessType());
        voucher.setInvoiced(true);
        // 从表信息
        voucher.setVoucherItems(getPurchaseVoucherItems(purchaseOrder, pick));

        // 更新收货状态
        purchaseOrder.setShipped();
        purchaseOrderRepository.saveAndFlush(purchaseOrder); // 因为状态机，这里要显式保存
        return voucher;
    }

    public Set<VoucherItem> getPurchaseVoucherItems(PurchaseOrder purchaseOrder, Pick pick) {
        Set<VoucherItem> voucherItems = new HashSet();
        Map<Long, PurchaseOrderItem> PurchaseOrderItemMap = purchaseOrder.getPurchaseItems().stream().collect(Collectors.toMap(PurchaseOrderItem::getId, PurchaseOrderItem -> PurchaseOrderItem));
        pick.getPickItems().forEach(
                (pickItem) -> {
                    VoucherItem voucherItem = new VoucherItem();
                    PurchaseOrderItem purchaseOrderItem = PurchaseOrderItemMap.get(Long.valueOf(pickItem.getOriginLine()));
                    if (purchaseOrderItem == null) {
                        throw new RuntimeException("未找到采购订单行：" + pickItem.getOriginLine());
                    }
                    voucherItem.setProduct(pickItem.getProduct());
                    voucherItem.setTax(getBean(TaxService.class).getPurchaseTax(purchaseOrder.getCompany(), purchaseOrder.getSupplier(), pickItem.getProduct()));
                    voucherItem.setOwner(purchaseOrder.getLocation().getCompany());
                    voucherItem.setUom(uomService.getUom(purchaseOrder.getCompany(), purchaseOrderItem.getProduct()));
                    // 回写交货数量
//                    purchaseOrderItem.delivery(pickItem.getQtyDone());
                    // 减采购在途数量
//                    productAccountService.setProductPurchasingWay(pickItem.getProduct(),pick.getLocation(), pickItem.getUom(),-1 * pickItem.getQtyDone(),pick.getCompany());
                    voucherItem.setProductQty(purchaseOrderItem.computeQtyUnit(pickItem.getQtyDone()));
                    voucherItem.setPriceUnit(purchaseOrderItem.computePriceUnit());
                    voucherItem.setOriginItemId(String.valueOf(purchaseOrderItem.getId()));
                    voucherItem.setSourceItemId(String.valueOf(pickItem.getId()));
                    voucherItems.add(voucherItem);
                }
        );
        this.updateOldCGDD(purchaseOrder, pick);
        return voucherItems;
    }

    /**
     * 修改老框架入库数量
     * @param purchaseOrder
     * @param pick
     */
    private void updateOldCGDD(PurchaseOrder purchaseOrder, Pick pick) {
        if (StringUtils.isEmpty(purchaseOrder.getOrigin())) return;
        String sourceType = purchaseOrder.getSourceType();
        PurchaseOrder originPurchaseOrder = purchaseOrderRepository.findOne(purchaseOrder.getOrigin());
        if (!"CD0".equals(sourceType) && !"Redemption".equals(sourceType)) return;
        if ("Redemption".equals(sourceType) && (originPurchaseOrder == null || !"CD0".equals(originPurchaseOrder.getSourceType()))) return;

        String cgddh = purchaseOrder.getSource();
        if ("Redemption".equals(sourceType)) cgddh = purchaseOrder.getSupplierRef();
        if (StringUtil.isEmpty(cgddh)) return;

        JSONObject returnData = new JSONObject();
        try {
            returnData = purchaseService.formatCGDD(pick, cgddh);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        SpringManager.getBean(OutboxSubscriberService.class).commonSendRequest("local:PurchaseService.updateOldRKSL", "CGDDH:" + purchaseOrder.getId(), returnData);
    }


}


























